package com.zzyl.service.impl;

import com.google.common.collect.Lists;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description MemberServiceImpl
 * @Author Wen Jie
 * @Date 2024-09-12
 */
@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private WeChatService weChatService;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    static ArrayList DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //调取微信api,获取openId
        String openId = weChatService.getOpenId(userLoginRequestDto.getCode());
        //根据openId查询用户信息
        Member member = memberMapper.selectByOpenId(openId);
        //如果用户为空，则创建用户
        if(ObjectUtil.isEmpty(member)){
            member = Member.builder().openId(openId).build();
        }
        //调用微信api获取用户手机号
        String phone = weChatService.getPhone(userLoginRequestDto.getPhoneCode());

        saveOrUpdate(member,phone);
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID, member.getId());
        claims.put(Constants.JWT_USERNAME, member.getName());

        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getName());
        return loginVo;
    }

    private void saveOrUpdate(Member member,String phone){
        //判断获取的手机号与数据库中的手机号是否一致
        if(ObjectUtil.notEqual(member.getPhone(),phone)){
            member.setPhone(phone);
        }
        //判断id是否存在
        if(ObjectUtil.isNotEmpty(member.getId())){
            memberMapper.update(member);
            return;
        }
        //保存新用户，创建随机昵称
        String nickName = DEFAULT_NICKNAME_PREFIX.get((int)(Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                + StringUtils.substring(phone,7);
        member.setName(nickName);
        memberMapper.save(member);
    }
}
